package com.fortune.rainshineservice.controller;

import com.fortune.rainshinecommon.base.MsgModel;
import com.fortune.rainshinecommon.entity.StatTopTenEntity;
import com.fortune.rainshinecommon.enums.ResultCode;
import com.fortune.rainshinecommon.query.StatQuery;
import com.fortune.rainshinecommon.util.DateUtils;
import com.fortune.rainshineservice.service.StatService;
import com.fortune.rainshineservice.service.impl.StatTask;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @program: rainShine
 * @description:
 * @author: tangyn
 * @create: 2019-06-15
 **/
@RestController
@RequestMapping("/stat")
public class StatController {
    private static final Logger logger = LoggerFactory.getLogger(StatController.class);

    @Autowired
    private StatService statService;

    @Autowired
    private StatTask statTask;

    @PostMapping("/merchantMonthStat")
    public MsgModel merchantMonthStat(@RequestBody StatQuery query) {
        Map<String, String> map = getStatTime(query.getBeginTime(), query.getEndTime());
        String beginTime = map.get("beginTime");
        String endTime = map.get("endTime");
        List<StatTopTenEntity> snceList = statService.selectMerchatStat(beginTime, endTime);
        if (!snceList.isEmpty()) {
            snceList = snceList.stream().filter(e -> Double.valueOf(e.getShowNum()) > 0.0).collect(Collectors.toList());
        }
        if(StringUtils.isBlank(query.getChannel())) {
            return new MsgModel(snceList.size(), snceList);
        }else {
            return this.parmMake(snceList);
        } 
    }

    /**
     * 门店新增会员前十排名
     *
     * @param query
     * @return
     */
    @PostMapping("/getShopNewCustomerStat")
    public MsgModel getShopNewCustomerStat(@RequestBody StatQuery query) {
        Map<String, String> map = getStatTime(query.getBeginTime(), query.getEndTime());
        String beginTime = map.get("beginTime");
        String endTime = map.get("endTime");
        List<StatTopTenEntity> snceList = Optional.ofNullable(statService.getShopNewCustomerStat(beginTime, endTime)).orElse(Lists.newArrayList());
        if (!snceList.isEmpty()) {
            snceList = snceList.stream().filter(e -> Integer.parseInt(e.getShowNum()) > 0).collect(Collectors.toList());
        }
        if(StringUtils.isBlank(query.getChannel())) {
            return new MsgModel(snceList.size(), snceList);
        }else {
            return this.parmMake(snceList);
        } 
    }

    /**
     * 门店采购产品前十排名
     *
     * @param query
     * @return
     */
    @PostMapping("/getShopBuyStat")
    public MsgModel getShopBuyStat(@RequestBody StatQuery query) {
        Map<String, String> map = getStatTime(query.getBeginTime(), query.getEndTime());
        String beginTime = map.get("beginTime");
        String endTime = map.get("endTime");
        List<StatTopTenEntity> snceList = Optional.ofNullable(statService.getShopBuyStat(beginTime, endTime)).orElse(Lists.newArrayList());
        if (!snceList.isEmpty()) {
            snceList = snceList.stream().filter(e -> Double.valueOf(e.getShowNum()) > 0.0).collect(Collectors.toList());
        }
        if(StringUtils.isBlank(query.getChannel())) {
            return new MsgModel(snceList.size(), snceList);
        }else {
            return this.parmMake(snceList);
        } 
    }

    @PostMapping("/statYesterday")
    public MsgModel statYesterday() {
        statTask.dayStat();
        return new MsgModel(ResultCode.SUCCESS);
    }

    private Map<String, String> getStatTime(String beginTime, String endTime) {
        if (StringUtils.isNotBlank(beginTime)) {
            Preconditions.checkArgument(DateUtils.validYYYYMM(beginTime), "年月格式不正确");
        }
        if (StringUtils.isNotBlank(endTime)) {
            Preconditions.checkArgument(DateUtils.validYYYYMM(endTime), "年月格式不正确");
        }
        if (StringUtils.isBlank(beginTime) && StringUtils.isBlank(endTime)) {
            beginTime = DateUtils.getLastMonth();
            endTime = DateUtils.getLastMonth();
        } else {
            if (StringUtils.isBlank(endTime)) {
                endTime = beginTime;
            }
            if (StringUtils.isBlank(beginTime)) {
                beginTime = endTime;
            }
            Preconditions.checkArgument(DateUtils.compareYYYYMM(endTime, beginTime), "开始日期不能大于结束日期");
        }
        Map<String, String> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        return map;
    }

    /**
     * @Title: merchantWeb
     * @Description: web用招商排名前十
     * @author zhangxin
     * @phone 17561783855
     * @date 2019年8月2日
     */
    @SuppressWarnings({ "rawtypes", "unused" })
    private MsgModel parmMake(List<StatTopTenEntity> snceList) {
        try {
            //底部显示名称
            List<String> xAxis = new ArrayList<>();
            //柱状数据
            List<String> seriesleft = new ArrayList<>();
            if(!snceList.isEmpty()){
                //拼装参数
                IntStream.range(0,snceList.size()).forEach(i->{
                    xAxis.add(i, snceList.get(i).getColumnName());
                    seriesleft.add(i, snceList.get(i).getShowNum());
                });
            }
            Map<String,List> result = new HashMap<>();
            result.put("xAxis", xAxis);
            result.put("seriesleft", seriesleft);
            return new MsgModel(snceList.size(), result);
        } catch (Exception ex) {
            logger.error("stat parmMake Exception ====> {}", ex);
            return new MsgModel(ResultCode.FAILURE);
        }
    }

    /**
     * 每日统计表重跑
     */
    @GetMapping(path="/dayReRun")
    public MsgModel dayReRun(){
        return statService.dayReRun();
    }

    /**
     * 每日统计表重跑
     */
    @GetMapping(path="/monthReRun")
    public MsgModel monthReRun(){
        return statService.monthReRun();
    }
}
